package com.openfeint.actionCollection;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.util.Log;

import com.openfeint.api.OpenFeintSettings;
import com.openfeint.internal.OpenFeintInternal;
import com.openfeint.internal.SyncedStore;
import com.openfeint.internal.request.OrderedArgList;

public class DataFileManager implements Symbol {

	/**
	 * 决定是否使用sql存储数据，设false即使用文本存储 *文本存储并没有完全实现*
	 * 
	 * */
	final static boolean useSql = true;
	private static String TAG = "DataFileManager";
	private static OpenFeintSettings settings = null;
	private static boolean isInitialized = false;
	private static Context mContext = null;
	private static DBHelper helper = null;
	private static boolean gameState = false;// 游戏状态
	private static long lastTime = 0l;
	private static long preTime = -1l;
	private static String createTime = null;
	private static int delcount = 0;

	public static void initialize(Context c, OpenFeintSettings settings) {
		setSettings(settings);
		mContext = c;
		helper = new DBHelper(c);
		uploadData();
		isInitialized = true;
	}

	/**
	 * 上传数据
	 * */
	public static void Open() {
		uploadData();
	}

	/**
	 * 上传数据，但不会删除已经上传的数据 在收到服务器消息后调用onResponseSucceed()方法删除
	 * 
	 * */
	public static void uploadData() {

		Log.d(TAG, "UPLOAD DATA");
		OrderedArgList args = new OrderedArgList();
		StringBuffer sb = new StringBuffer();
		List<String> s = loadData(mContext, null);
		Iterator<String> it = s.iterator();
		if (it.hasNext() == true) {
		while (it.hasNext()) {

			sb.append(it.next());
			sb.append(ROW_SEPERATOR);
		}
		args.put("arg0", sb.toString());
		Log.d("my_arg", ""+sb.toString());
		ActionRequest mq = new ActionRequest(args);
		mq.launch();
		}else{
			Log.d("my_arg", "no_data");
		}
		
	}

	/**
	 * 设定appkey
	 * 
	 * */
	public static void setSettings(OpenFeintSettings settings) {
		DataFileManager.settings = settings;
	}

	public static void resume(Context c) {
		commitData(c, ONRESUME);
	}

	public static void pause(Context c) {
		commitData(c, ONPAUSE);
	}

	private static void commitData(Context c, String state) {
		if (isInitialized == false) {
			Log.d(TAG, "DataFileManager has not been initialized ");
			return;
		}

		String corState = gameState == true ? ONPAUSE : ONRESUME;
		if (corState.equals(state)) {
			
			if (test)
				Log.d(TAG, "StateCorrect State = " + state);
			Long curTime = System.currentTimeMillis();
			if (preTime == -1l) {
				if (test)
					Log.d(TAG, "FirstTime,setPreTime");
				checkLast(c);
				createTime = getFormatTimeString();
				if (gameState == true) {
					if (test)
						Log.d(TAG, "ErrorState,gameState = true");
				}
				;// error
				gameState = true;

			} else {

				int interval = (int) (curTime - preTime);
				if (gameState == false) {
					if (test)
						Log.d(TAG, "false->true,");
					if (interval < MAXINTERVAL) {
						if (test)
							Log.d(TAG, "interval ok :" + interval);
						lastTime += interval;
					} else {

						if (test)
							Log.d(TAG, "interval too long :" + interval
									+ "  savedata");
						// savedata
						saveData(c, state);
						// resetdata
						resetData(c);
						createTime = getFormatTimeString();

					}
					gameState = true;

				} else {
					if (test)
						Log.d(TAG, "true->false SaveLastTime");

					lastTime += interval;
					SharedPreferences sp = c.getSharedPreferences(TAG, 0);
					SharedPreferences.Editor se = sp.edit();
					se.putLong(LASTTIME, lastTime).commit();
					se.putString(CREATETIME, createTime).commit();


					gameState = false;
				}

			}
			preTime = curTime;

		} else {
			// error
			if (test)
				Log.d(TAG, "errorState State = " + state);
			// resttdata
			if (gameState = true) {
				resetData(c);
				gameState = true;
				createTime = getFormatTimeString();
			} else {
				resetData(c);
			}
		}
		
		
	}

	/**
	 * 检测是否有启动->关闭的状态记录 如果有，则写入一次记录
	 * 
	 * */
	private static void checkLast(Context c) {

		SharedPreferences sp = c.getSharedPreferences(TAG, 0);
		Long last = sp.getLong(LASTTIME, 0);
		if (last != 0) {
			lastTime = last;
			createTime = sp.getString(CREATETIME, null);
			if (test)
				Log.d(TAG, "find unsaved Data ,daveData:" + createTime);
			saveData(c, TAG);
			resetData(c);

		}

	}

	private static void resetData(Context c) {
		Log.d(TAG, "resteData");
		gameState = false;// 游戏状态
		lastTime = 0l;
		preTime = -1l;
		createTime = null;

		SharedPreferences sp = c.getSharedPreferences(TAG, 0);
		SharedPreferences.Editor se = sp.edit();
		se.putLong(LASTTIME, lastTime).commit();

	}

	private static void saveData(Context c, String state) {
		String[] s = createTime.split(COL_SEPERATOR);
		String sData = s[0] + COL_SEPERATOR + settings.id + COL_SEPERATOR
				+ getDeviceID(c) + COL_SEPERATOR + s[1] + COL_SEPERATOR
				+ lastTime / 1000;// date,appid,deviceid,time,lastetime
		if (test)
			Log.d(TAG, "saveOneSession:" + sData);
		saveData(c, s[0], sData);
	}
	

	/**
	 * 获取设备唯一id
	 * 
	 * */
	public static String getDeviceID(Context c) {

		return OpenFeintInternal.getInstance().getUDID();

	}

	/**
	 * 获取当前时间
	 * */
	public static String getFormatTimeString() {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy"
				+ DATE_SEPERATOR + "MM" + DATE_SEPERATOR + "dd" + COL_SEPERATOR
				+ "HH" + TIME_SEPERATOR + "mm" + TIME_SEPERATOR + "ss");// yyyy-mm-dd&HH:MM:SS

		Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
		return formatter.format(curDate);

	}

	/**
	 * @param path
	 *            这个是文本存储时使用的属性，使用sql存储是无作用，可以传null
	 * 
	 * 
	 * */
	public static void saveData(Context c, String path, String sData) {
		if (!useSql)
			try {
				FileOutputStream outStream = c.openFileOutput(path,
						Context.MODE_APPEND);
				outStream.write((sData + "\n").getBytes());
				outStream.close();

			} catch (IOException e) {
				e.printStackTrace();
			}
		else {
			ContentValues values = new ContentValues();
			values.put("name", sData);
	
			helper.insert(values);
		}

	}

	/**
	 * @param path
	 *            这个是文本存储时使用的属性，使用sql存储是无作用，可以传null
	 * 
	 */
	public static List<String> loadData(Context c, String path) {
		if (!useSql) {
			try {
				List<String> alData = new ArrayList<String>();
				FileInputStream inStream = c.openFileInput(path);
				ByteArrayOutputStream stream = new ByteArrayOutputStream();

				byte[] buffer = new byte[1024];
				byte buf = 0;
				int length = -1;
				int i = 0;

				while ((buf = (byte) inStream.read()) != -1) {
					if (buf != '\n') {
						buffer[i++] = buf;
					} else {
						stream.write(buffer, 0, i);
						alData.add(stream.toString());
						stream.reset();
						i = 0;
					}
				}
				stream.close();
				inStream.close();

				return alData;
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				return null;
			} catch (IOException e) {
				return null;
			}

		} else {
			// database
			List<String> ls = new ArrayList<String>();
			Cursor dbc = helper.query();

			delcount = 0;
			while ((dbc.moveToNext()) && (delcount < MAXCOUNT)) {
				delcount++;
				ls.add(dbc.getString(1));
				
			}
			dbc.close();

			return ls;
		}
	}

	/**
	 * 删除数据库delcount条数据
	 * 
	 * 
	 * */
	public static void onResponseSucceed() {
		if (delcount > 0) {
			if (test)
				Log.d(TAG, "delcount=" + delcount);
			helper.delAll(delcount);
		}

	}

}
